package com.cscec.omega.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.cscec.omega.service.*;
import com.cscec.omega.utils.RequestUtil;
import com.cscec.omega.utils.ResponseEntity;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;

/**
 * 通用接口
 * 接收数据上传
 *
 */
@RestController
@RequestMapping("/api")
public class UniversalController {

    private static Logger logger = LoggerFactory.getLogger(UniversalController.class);

    @Autowired
    private UniversalService universalService;


    /**
     * 1、获取签名 ?appId=hanxunGate&secretKey=NOI234nseSDDcc 有效期24小时
     * 2、上传数据
     * 3、上传图片
     * 4、上传数据+图片
     * 5、图片下载
     * 6、jsonSchema
     * @return
     */

    /**
     * 获取签名
     * @return
     */
    @PostMapping("/auth/sign")
    public ResponseEntity getSign(){
        return new ResponseEntity(20000, "ok", "6a220a09-3c9e-48ca-830d-c2ad1acf4c13");
    }

    /**
     * 上传数据
     * @param appId
     * @param moduleId
     * @param jsonObject
     * @return
     */
    @PostMapping("/{appId}/{moduleId}/uploadData")
    public ResponseEntity uploadData(@PathVariable("appId") String appId, @PathVariable("moduleId") String moduleId, @RequestBody JSONObject jsonObject) {
        String collectionName = appId+"_"+moduleId;
        JSONObject result = universalService.save(jsonObject, collectionName);
        return new ResponseEntity(20000, "数据上传成功", result.getString("objectId"));
    }

    /**
     * 上传文件
     * @param appId
     * @param moduleId
     * @param file
     * @return
     */
    @PostMapping("/{appId}/{moduleId}/uploadFile")
    public ResponseEntity uploadFile(MultipartFile file, @PathVariable("appId") String appId, @PathVariable("moduleId") String moduleId) {
        String collectionName = appId+"_"+moduleId;
        String result = universalService.save(file, collectionName);
        return new ResponseEntity(20000, "数据上传成功", result);
    }

    /**
     * 上传文件和数据
     * @param file
     * @param request
     * @param appId
     * @param moduleId
     * @return
     */
    @PostMapping("/{appId}/{moduleId}/upload")
    public ResponseEntity uploadFileAndData(MultipartFile file, HttpServletRequest request, @PathVariable("appId") String appId, @PathVariable("moduleId") String moduleId){
        logger.info("appId: {}, moduleId: {}", appId, moduleId);
        String jsonStr = JSON.toJSONString(RequestUtil.request2Map(request));
        JSONObject jsonObject = JSON.parseObject(jsonStr);
        String collectionName = appId+"_"+moduleId;
        JSONObject result = universalService.save(file, jsonObject, collectionName);
        return new ResponseEntity(20000, "数据上传成功", result);
    }
}
